package cn.itcast.crm.service.impl;

import cn.itcast.crm.dao.CustomerRespository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerRespository customerRespository;
    @Override
    public List<Customer> findNoAssociationCustomers() {
        return customerRespository.findByFixedAreaIdIsNull();
    }

    @Override
    public List<Customer> findHasAssociationCustomerFixedAreaCutomers(String fixedAreaId) {
        return  customerRespository.findByFixedAreaId(fixedAreaId);
    }

    @Override
    public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
    	//先接触关联
    	customerRespository.clearFixedAreaId(fixedAreaId);
    	
    	//如果为空直接返回
    	if(StringUtils.isBlank(customerIdStr)){
    		return ;
    	}
        String[] customerIdArray = customerIdStr.split(",");
        for (String idStr:
             customerIdArray) {
                Integer id = Integer.parseInt(idStr);
                customerRespository.updateFixedAreaId(fixedAreaId,id);
        }
    }

	@Override
	public void regist(Customer customer) {
		customerRespository.save(customer);
		
	}

	@Override
	public Customer findByTelephone(String telephone) {
		// TODO Auto-generated method stub
		return customerRespository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRespository.updateType(telephone);
		
	}

    @Override
    public Customer login(String telephone, String password) {
        return customerRespository.findByTelephoneAndPassword(telephone,password);
    }

    @Override
    public String findFixedAreaIdByAddress(String address) {
        return customerRespository.findFixedAreaIdByAddress(address);
    }
}
